<template>
	<view class="page has-fixed-footer">
		<page-header :showPlaceHolder="false" :showTitle="false"></page-header>
		<!-- 内容 -->
		<view class="content">
			<view class="title">
				{{store.getters.userType == '2' ? '供应商认证':'供应链认证'}}
			</view>
			<view class="prompt">
				{{store.getters.userType == '2' ? '完善以下资料，通过供应商认证':'完善以下资料，通过供应链认证'}}
			</view>
			<fui-steps :items="items" :fontWeight="550" :isMark="false" :current="current" :size="24" direction="row"
				:isWait="true" :lineThrough="true" color="#999999" nodeColor="#999999"></fui-steps>
			<fui-section descrColor="#666666" title="负责人认证" isLine color="#333333" lineWidth="4px"
				marginTop="30"></fui-section>
			<view style="display: flex; justify-content: space-between; padding: 20rpx;">
				<upload-image size="small" type="front" :defaultList="form.adminCardFront ? [form.adminCardFront] : []"
					@uploaded="uploadedCardFront"></upload-image>
				<upload-image size="small" type="back" :defaultList="form.adminCardBack ? [form.adminCardBack] : []"
					@uploaded="uploadedCardBack"></upload-image>
			</view>
			<view class="fui-wrap">
				<fui-form ref="formRef" :model="form" :top="store.getters.statusBarHeight">
					<fui-form-item label="姓名" labelWeight="600" labelWidth="200" :left="0" labelSize="28" prop="adminName">
						<fui-input :borderBottom="false" color="#333" size="28" :padding="[0]" placeholder="请输入负责人姓名"
							v-model="form.adminName"></fui-input>
					</fui-form-item>
					<fui-form-item label="身份证号" labelWeight="600" labelWidth="200" :left="0" labelSize="28"
						prop="adminIdCard">
						<fui-input :borderBottom="false" color="#333" size="28" :padding="[0]"
							placeholder="请输入负责人身份证号" v-model="form.adminIdCard"></fui-input>
					</fui-form-item>
					<fui-form-item label="手机号码" labelWeight="600" :left="0" labelWidth="200" labelSize="28"
						prop="adminPhone">
						<fui-input :borderBottom="false" color="#999" size="28" :padding="[0]"
							placeholder="请输入负责人联系方式" v-model="form.adminPhone" disabled></fui-input>
					</fui-form-item>
					<!-- <fui-form-item label="登录密码" labelWeight="600" :left="0"
						labelWidth="200" labelSize="28" prop="loginPsw">
						<fui-input :borderBottom="false" color="#999" size="28" :padding="[0]"
							placeholder="请输入登录密码" v-model="form.loginPsw" disabled></fui-input>
					</fui-form-item> -->
				</fui-form>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="ui-fixed-footer ui-fixed-footer__white">
			<fui-button :disabled="!form.adminIdCard" height="78rpx" :margin="['294rpx','0','0','0 ']"
				disabledBackground="#DFDFDF" disabledColor="#666666" background="var(--fui-color-primary)" bold
				@click="validForm">提交</fui-button>
		</view>

		<modal-agreement ref="agreementRef" @confirm="submit"></modal-agreement>

		<!-- 成功提示 -->
		<fui-backdrop :show="isShow" closable @click="close">
			<Register :childProp="parentText" @end="end" @nextStep="nextStep"></Register>
		</fui-backdrop>
	</view>
</template>

<script setup>
import { ref, computed, inject, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import { getDefaultPassword } from '@/utils/tools'
import pageHeader from '@/components/header'
import uploadImage from '@/components/upload/image'
import Register from '@/components/popup/register'
import ModalAgreement from './Agreement'
import systemApi from '@/api/system'
import supplierApi from '@/api/supplier'

const tab = inject('$tab')
const modal = inject('$modal')
const store = useStore()

// 步骤条
const current = ref(2)
const items = ref([{
	title: '公司认证',
	text: '1'
}, {
	title: '法人认证',
	text: '2'
}, {
	title: '负责人认证',
	text: '3'
}])

// 缓存数据
const businessForm = uni.getStorageSync('business') // 营业执照表单
const legalpersonForm = uni.getStorageSync('LegalPerson') // 法人表单
const categoryList = store.getters.userType === '2' ? businessForm.categoryValue.split('|') : []
const categoryIds = categoryList.map(item => {
	return item.split(',')[1]
})

// 表单
const form = ref({
	adminCardFront: '', // 身份证正面 
	adminCardBack: '', // 身份证反面
	adminName: '',
	adminIdCard: '', // 负责人身份证号
	adminPhone: '' // 负责人手机号
})
const formRef = ref(null)
const rules = ref([
	{
		name: 'adminName',
		rule: ['required', 'minLength:2'],
		msg: ['请输入负责人姓名', '姓名必须2个或以上字符']
	}, {
		name: 'adminIdCard',
		rule: ['required', 'isIdCard'],
		msg: ['请输入负责人身份证号', '请输入正确身份证号']
	}, {
		name: 'adminPhone',
		rule: ['required', 'isMobile'],
		msg: ['请输入负责人联系方式', '请输入正确的手机号码']
	}
])

watch(form.value, (newValue) => {
	if (newValue.adminName && newValue.adminName.length >= 2 && newValue.adminPhone && newValue.adminPhone.length >= 11) {
		form.value.loginPsw = getDefaultPassword(newValue.adminName, newValue.adminPhone)
	}
}, {
	immediate: true
})

onLoad(() => {
	getAdminDetail()
})

// 获取负责人信息
const adminInfo = ref({
	adminName: '',
	adminPhone: ''
})
const adminApiUrl = computed(() => {
	let apiUrl = ''
  if (store.getters.userType === '1') apiUrl = 'getSupplyAdminDetail'
  if (store.getters.userType === '2') apiUrl = 'getSupplierAdminDetail'
  return apiUrl
})
const getAdminDetail = () => {
	supplierApi[adminApiUrl.value](store.getters.companyId).then((res) => {
		if (res.code == 0 && res.data) {
			Object.keys(adminInfo.value).forEach((key) => {
				adminInfo.value[key] = res.data[key]
			})
		
			Object.keys(form.value).forEach((key) => {
				form.value[key] = res.data[key]
			})
			if (legalpersonForm.isSamePerson) {
				form.value = {
					adminCardFront: legalpersonForm.idcFront,
					adminCardBack: legalpersonForm.idcBack,
					adminName: legalpersonForm.corporationName,
					adminIdCard: legalpersonForm.corporationIdCard,
					adminPhone: legalpersonForm.corporationPhone
				}
			}
		}
	})
}

// 上传
const uploadedCardFront = async (e) => {
	if (e[0]) {
		try {
			modal.loading()
			const res = await systemApi.uploadidcard({
				imageUrl: e[0]
			})
			modal.closeLoading()
			form.value.adminCardFront = e[0]
			if (res.code == 0) {
				let obj = JSON.parse(res.data)
				form.value.adminName = obj['姓名']
				form.value.adminIdCard = obj['公民身份号码']
			}
		} catch (err) {
			modal.closeLoading()
			modal.msgError('读取错误，请确认上传正确的身份证件！')
		}
	}
}
const uploadedCardBack = async (e) => {
	if (e[0]) {
		form.value.adminCardBack = e[0]
	}
}

const isShow = ref(false)
const parentText = ref('')
const successBack = async () => {
	if (store.getters.userType === '2') {
		store.dispatch('LogOut')
	} else {
		await store.dispatch('GetUserInfo')
		tab.reLaunch('/pages/index')
	}
}
const end = () => {
	successBack()
}
const nextStep = () => {
	successBack()
}
const close = () => {
	isShow.value = false
}

// 提交
const agreementRef = ref(null)
const validForm = async () => {
	if (!form.value.adminCardFront) {
		modal.msgError('请上传负责人身份证正面照片！')
		return
	}
	if (!form.value.adminCardBack) {
		modal.msgError('请上传负责人身份证反面照片！')
		return
	}
	if (form.value.adminName !== adminInfo.value.adminName || form.value.adminPhone !== adminInfo.value.adminPhone) {
		modal.msgError('负责人信息请与邀约时保持一致！')
		return
	}

	const validRes = await formRef.value.validator(form.value, rules.value)
	if (validRes.isPassed) {
		agreementRef.value.show()
	}
}
const submitApiUrl = computed(() => store.getters.userType == '2' ? 'updateSupplier' : 'updateSupply')
const submit = () => {
	form.value = {
		...businessForm,
		...legalpersonForm,
		...form.value
	}
	if (store.getters.userType == '2') {
		form.value.id = store.getters.companyId
		form.value.isSamePerson = legalpersonForm.isSamePerson ? '1' : '0'
		form.value.yunyfw = businessForm.rangeValue
		form.value.yunypl = businessForm.categoryValue
	} else {
		form.value.id = store.getters.companyId
		form.value.name = businessForm.companyName
		form.value.isSamePerson = legalpersonForm.isSamePerson ? 'Y' : 'N'
		form.value.corporationFaceCheck = 'Y'
		form.value.adminFaceCheck = 'Y'
		// form.value.manageScope = businessForm.rangeValue
		// form.value.categoryRange = categoryIds.join(',')
		form.value.companyType = '10'
	}
	systemApi[submitApiUrl.value](form.value).then((res) => {
		if (res.code == 0) {
			parentText.value = store.getters.userType === '2' ? 'submit' : 'supplySuccess'
			isShow.value = true
		}
	})
}
</script>

<style lang="scss" scoped>
.page {
	position: relative;
	min-height: 100%;

	.content {
		margin: 36rpx;

		.title {
			font-size: 40rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: bold;
			color: #333333;
		}

		.prompt {
			font-size: 24rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			color: #999999;
			margin-top: 20rpx;
		}

		.login-agreement {
			display: flex;
			align-items: center;
			margin-top: 30rpx;

			.fui-label__box {
				display: flex;
				align-items: center;

				.fui-checkbox__input {
					margin-right: 12rpx;
				}
			}
		}

		::v-deep.fui-steps__wrap {
			margin: 60rpx auto;
		}

		::v-deep.fui-sections__wrap {
			padding: 0 !important;
		}

		:deep(.fui-form__msg-wrap) {
			z-index: 11000;
		}

		::v-deep.fui-form__wrap-inner {
			padding: 0 !important;
		}

		::v-deep.uni-input-input {
			font-weight: bold;
		}

		.ask {
			width: 100%;
			padding: 22rpx 20rpx 24rpx 28rpx;
			border-radius: 24rpx 24rpx 24rpx 24rpx;
			background-color: #fff3e4;
			box-sizing: border-box;

			.ask-title {
				font-size: 28rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: bold;
				color: #333333;
			}

			.ask-content {
				margin-top: 16rpx;
				font-size: 24rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				color: #999999;

				text {
					color: #f95a5a;
				}
			}
		}

		::v-deep.textarea-box .fui-form__wrap-inner {
			display: initial !important;
		}

		.cycle-box {
			display: flex;
			align-items: center;
			margin-top: 20rpx;

			.cycle {
				width: 160rpx;
				height: 64rpx;
				background: #f5f7fe;
				border-radius: 0rpx 0rpx 0rpx 0rpx;
				opacity: 1;
				border: 2rpx solid #e7ebfb;
				font-size: 24rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				color: #333333;
				text-align: center;
				line-height: 64rpx;
				margin-right: 20rpx;
				position: relative;
			}

			.cycle-active {
				font-weight: bold;
				color: var(--fui-color-primary);
				border: 2rpx solid var(--fui-color-primary);
			}

			.cycleimg {
				width: 30rpx;
				height: 27rpx;
				display: block;
				position: absolute;
				right: 0;
				bottom: 0;
			}
		}
	}
}
</style>